import { config } from '../config/config';
import Vue from 'vue'
import axios from 'axios';
import { Message } from 'element-ui';
import router from '../router';
import { Loading } from 'element-ui';

// 创建一个axios实例
const service = axios.create({
    headers: {
        'content-type': 'application/json;charset=UTF-8',
        'Authorization': 'bearer ' + localStorage.getItem("token")
    },
    baseURL: config.requestApi,
    // withCredentials: true,
    timeout: 5000
})

let loading = false
function openLoading() {
    loading = Vue.prototype.$loading({
        lock: true,
        text: '努力加载中...',
        background: 'rgba(0,0,0,0.7)'
    })
}
function closeLoading() {
    loading && loading.close()
}

// 添加请求拦截器
service.interceptors.request.use(config => {
    // openLoading(config.loadingDom);
    // 在发送请求之前做某事，比如说 设置token
    config.headers['Authorization'] = 'bearer ' + localStorage.getItem("token")
    return config;
}, error => {
    // 请求错误时做些事
    return Promise.reject(error);
});

// 添加响应拦截器
service.interceptors.response.use(response => {
    // closeLoading();
    // 如果返回的状态不是200 就主动报错
    if (response.data.code != config.successCode) {
        Message.error({
            dangerouslyUseHTMLString: true,
            message: response.data.msg,
        });

        if (response.data.code == 5060) {//token问题一律跳转登录页
            localStorage.clear();
            router.push('/login')
        }
        return Promise.reject(response.data.msg)
    }

    return response.data;
}, error => {
    // closeLoading();
    Message.error({
        dangerouslyUseHTMLString: true,
        message: error.response.data.msg,
    });


    return Promise.reject(error.response.data.msg); // 返回接口返回的错误信息
})

export default service